/**
 * A Picker field that contains a tree panel on its popup, enabling selection of tree nodes.
 */
Ext.define('Ext.ux.MultiTreePicker', {
    extend: 'Ext.form.field.Picker',
    xtype: 'multitreepicker',
    
    uses: [
        'Ext.tree.Panel'
    ],

    triggerCls: Ext.baseCSSPrefix + 'form-arrow-trigger',

    config: {
        /**
         * @cfg {Ext.data.TreeStore} store
         * A tree store that the tree picker will be bound to
         */
        store: null,

        /**
         * @cfg {String} displayField
         * The field inside the model that will be used as the node's text.
         * Defaults to the default value of {@link Ext.tree.Panel}'s `displayField` configuration.
         */
        displayField: null,

        /**
         * @cfg {Array} columns
         * An optional array of columns for multi-column trees
         */
        columns: null,

        /**
         * @cfg {Boolean} selectOnTab
         * Whether the Tab key should select the currently highlighted item. Defaults to `true`.
         */
        selectOnTab: true,

        /**
         * @cfg {Number} maxPickerHeight
         * The maximum height of the tree dropdown. Defaults to 300.
         */
        maxPickerHeight: 300,

        /**
         * @cfg {Number} minPickerHeight
         * The minimum height of the tree dropdown. Defaults to 100.
         */
        minPickerHeight: 100
    },
   
    editable: false,

    /**
     * @event select
     * Fires when a tree node is selected
     * @param {Ext.ux.TreePicker} picker        This tree picker
     * @param {Ext.data.Model} record           The selected record
     */

    initComponent: function() {
        var me = this;

        me.callParent(arguments);
        me.mon(me.store, {
            scope: me,
            load: me.onLoad,
            update: me.onUpdate
        });
    },

    /**
     * Creates and returns the tree panel to be used as this field's picker.
     */
    createPicker: function() {
        var me = this,
            picker = new Ext.tree.Panel({
                shrinkWrapDock: 2,
                store: me.store,
                floating: true,
                displayField: me.displayField,
                columns: me.columns,
                minHeight: me.minPickerHeight,
                maxHeight: me.maxPickerHeight,
                manageHeight: false,
                shadow: false,
                rootVisible:false,
                listeners: {
                    scope: me,
                    itemclick: me.onItemClick
                },
                viewConfig: {
                    listeners: {
                        scope: me,
                        render: me.onViewRender
                    }
                }
            }),
            view = picker.getView();

        if (Ext.isIE9 && Ext.isStrict) {
            // In IE9 strict mode, the tree view grows by the height of the horizontal scroll bar when the items are highlighted or unhighlighted.
            // Also when items are collapsed or expanded the height of the view is off. Forcing a repaint fixes the problem.
            view.on({
                scope: me,
                highlightitem: me.repaintPickerView,
                unhighlightitem: me.repaintPickerView,
                afteritemexpand: me.repaintPickerView,
                afteritemcollapse: me.repaintPickerView
            });
        }
        return picker;
    },
    
    onViewRender: function(view){
        view.getEl().on('keypress', this.onPickerKeypress, this);
    },

    /**
     * repaints the tree view
     */
    repaintPickerView: function() {
        var style = this.picker.getView().getEl().dom.style;

        // can't use Element.repaint because it contains a setTimeout, which results in a flicker effect
        style.display = style.display;
    },

    /**
     * Handles a click even on a tree node
     * @private
     * @param {Ext.tree.View} view
     * @param {Ext.data.Model} record
     * @param {HTMLElement} node
     * @param {Number} rowIndex
     * @param {Ext.event.Event} e
     */
    onItemClick: function(view, record, node, rowIndex, e) {
        var checked = !record.data.checked;
        record.set('checked', checked);
        this.selectItem(record);
        this.onCheckChange(record, checked);
    },
    onCheckChange:function(node, checked) {
		this.setChildrenCheckedStatus(node, checked);
		this.updateParentCheckedStatus(node, checked);
	},
	setChildrenCheckedStatus : function(node, check) {
		var me = this;
		var len = node.childNodes.length;
		if (len <= 0 || node.get('disabled') === true) {
			if (node.get('disabled') === false)
				node.set('checked', check);
			this.selectItem(node);
			return node.get('checked') ? 1 : -1;
		} else {
			var sumcount = 0;
			for (var index = 0; index < len; index++) {
				var subnode = node.childNodes[index];

				subnode.set('checked', check)
				this.selectItem(node);
				sumcount = sumcount
						+ me.setChildrenCheckedStatus(subnode, check);
			}
			if (len === Math.abs(sumcount)) {
				me.unsetThirdState(node);
				node.set('checked', check);
				this.selectItem(node);
				return node.get('checked') ? 1 : -1;
			} else {
				me.setThirdState(node);
				return 0;
			}

		}
	},
	updateParentCheckedStatus : function(node, check) {
		var me = this;
		var nodeparent = node.parentNode;
		// if (!nodeparent || nodeparent===panel.getRootNode()) { return; }
		if (!nodeparent) {
			return;
		} else {
			var len = nodeparent.childNodes.length;
			var sumcount = 0;
			for (var index = 0; index < len; index++) {
				var subnode = nodeparent.childNodes[index];
				if (me.isThirdState(subnode)) {
					sumcount = sumcount + 0;
				} else {
					if (subnode.get('checked')) {
						sumcount = sumcount + 1;
					} else {
						sumcount = sumcount - 1;
					}
				}
			}
			if (len === Math.abs(sumcount)) {
				me.unsetThirdState(nodeparent);
				nodeparent.set('checked', check);
				this.selectItem(node);
			} else {
				me.setThirdState(nodeparent);
			}
			me.updateParentCheckedStatus(nodeparent, check);
		}
	},
	isThirdState : function(node) {
		return node.get('cls') == this.indeterminateCls;

	},

	setThirdState : function(node) {
		node.set('cls', this.indeterminateCls);
		node.set('checked', true);
		this.selectItem(node);
	},

	unsetThirdState : function(node) {
		node.set('cls', '');
	},

	getLeafIdSelections : function() {
		var me = this;

		try {
			var tree_selections = me.getView().getChecked(), result = [];

			Ext.Array.each(tree_selections, function(rec) {
				if (rec.get('id')) {
					result.push(rec.get('id'));
				}
			});

			return result;
		} catch (e) {
			debug('[error in accessPanel getSelections]');
			debug(e);
		}
	},

	setSelections : function(codes) {
		var ids = codes.split(",");
		var me = this;

		if (ids[0] && ids[0]['id']) {
			ids = Ext.Array.pluck(ids, 'id');
		}

		me.getRootNode().cascadeBy(
				function() {
					var currNode = this;
					if (currNode.get('leaf')) {
						currNode.set('checked',
								ids.indexOf(currNode.get('id')) > -1);
						me.updateParentCheckedStatus(currNode, ids
								.indexOf(currNode.get('id')) > -1);
					}
				});
	},
    /**
     * Handles a keypress event on the picker element
     * @private
     * @param {Ext.event.Event} e
     * @param {HTMLElement} el
     */
    onPickerKeypress: function(e, el) {
        var key = e.getKey();

        if(key === e.ENTER || (key === e.TAB && this.selectOnTab)) {
            this.selectItem(this.picker.getSelectionModel().getSelection()[0]);
        }
    },

    /**
     * Changes the selection to a given record and closes the picker
     * @private
     * @param {Ext.data.Model} record
     */
    selectItem: function(record) {
        var me = this;
        var records = me.picker.getView().getChecked();
        values = [];
        
        Ext.Array.each(records,
        function (rec) {
            //names.push(rec.get('text'));
            if(rec.get('id')!='Root' && rec.get('id').indexOf('extModel')== -1){
            	values.push(rec.get('id'));
            }
        });
        me.setValue(values.join(','));
        //me.setValue(record.get(this.valueField || 'id'));
        ////me.picker.hide();
        me.inputEl.focus();
        me.fireEvent('select', me, record)

    },

    /**
     * Runs when the picker is expanded.  Selects the appropriate tree node based on the value of the input element,
     * and focuses the picker so that keyboard navigation will work.
     * @private
     */
    onExpand: function() {
        var me = this,
            picker = me.picker,
            store = picker.store,
            value = me.value,
            node;

        var records = me.picker.getView().getChecked();     //当前所有选中节点
 
        //取消选择当前已选择节点
        Ext.Array.each(records,
            function (rec) {
                rec.set('checked', false);
            });
 
 
        var valueList = value.split(',');
        if (valueList.length > 0) {
 
            for (var i = 0; i < valueList.length; i++) {
                node = store.getNodeById(valueList[i]);
                node.set('checked', true);
                var nodePath = node.getPath('id');
                picker.getComponentLayout().owner.expandPath(nodePath, 'id');
            }
        }
         Ext.defer(function () {
            view.focus();
        }, 1);


    },

    /**
     * Sets the specified value into the field
     * @param {Mixed} value
     * @return {Ext.ux.TreePicker} this
     */
    setValue: function(value) {
        var me = this,
            record;

        me.value = value;

        if (me.store.loading) {
            // Called while the Store is loading. Ensure it is processed by the onLoad method.
            return me;
        }
            
         try {
            var rawValueList = new Array();
            if (value) {
                var valueList = value.split(',');
                for (var i = 0; i < valueList.length; i++) {
                    var rec = me.store.getNodeById(valueList[i]);
                    if (rec)
                        rawValueList[i] = rec.get(me.displayField)
                }
                me.setRawValue(rawValueList.join(','));
                //var hasOwnProp = me.store.hasOwnProperty('getRootNode');
                //record = value ? me.store.getNodeById(value) : (hasOwnProp ? me.store.getRootNode() : null);
                //me.setRawValue(record ? record.get(this.displayField) : '');
            } else {
                me.setRawValue('');
            }
        } catch (e) {
            me.setRawValue('');
        }

        return me;
    },
    
    getSubmitValue: function(){
        return this.value;    
    },

    /**
     * Returns the current data value of the field (the idProperty of the record)
     * @return {Number}
     */
    getValue: function() {
        return this.value;
    },

    /**
     * Handles the store's load event.
     * @private
     */
    onLoad: function() {
        var value = this.value;
        if (value) {
            this.setValue(value);
        } else {
            if (this.firstSelected) {
                if (records && records.length > 0) {
                    var record = records[0];
                    this.setValue(record.get(this.valueField));
                }
            }
        }
    },
    
    onUpdate: function(store, rec, type, modifiedFieldNames){
        var display = this.displayField;
        
        if (type === 'edit' && modifiedFieldNames && Ext.Array.contains(modifiedFieldNames, display) && this.value === rec.getId()) {
            this.setRawValue(rec.get(display));
        }
    },
    getSubmitData: function () {
        var me = this,
            data = null;
        if (!me.disabled && me.submitValue) {
            data = {};
            data[me.getName()] = '' + me.getValue();
        }
        return data;
    },
    onTriggerClick: function () {
        var me = this;
        //me.store.load();
        if (!me.readOnly && !me.disabled) {
            if (me.isExpanded) {
                me.collapse();
            } else {
                me.expand();
            }
            me.inputEl.focus();
        }
    }
});
